﻿using System;

namespace FlashPay.DAO.Impl
{
    using FlashPay.DAO.Interface;
    using FlashPay.EF;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request;
    using FlashPay.Entity.Request.Bank;
    using FlashPay.Entity.Response;
    using FlashPay.Entity.Response.Bank;
    using FlashPay.Entity.Response.BankCard;
    using FlashPay.Entity.Response.Company;
    using FlashPay.Util;
    using Microsoft.EntityFrameworkCore;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;

    public class BankDaoImpl : IDisposable, BankDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context">EF上下文</param>
        /// <param name="companyDao">公司</param>
        public BankDaoImpl(FlashPayContext context, CompanyDao companyDao, LogRecord logRecord, LogDao logDao)
        {
            _context = context;
            _companyDao = companyDao;
            _logRecord = logRecord;
            _logDao = logDao;
        }

        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
        }
        #endregion

        #region 根据银行卡信息
        /// <summary>
        /// 获取订单月份
        /// </summary>
        /// <param name="month"></param>
        /// <returns></returns>
        private string GetOrderMonth(long orderNo)
        {
            return orderNo.ToString().Substring(4, 2);
        }

        /// <summary>
        /// 根据银行卡信息
        /// </summary>
        public BankCard GetById(int bcId, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);
            return _flashPayContext.BankCard.Where(x => x.Bcid == bcId).FirstOrDefault();
        }

        /// <summary>
        /// 获取银行卡信息
        /// </summary>
        public BankCard GetBcInfo(string CardNumber, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);
            return _flashPayContext.BankCard.Where(x => x.CardNumber == CardNumber).FirstOrDefault();
        }

        #endregion

        #region 新增行卡信息
        /// <summary>
        /// 新增行卡信息
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public int Add(BankCard model, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);
            _flashPayContext.BankCard.Add(model);
            _flashPayContext.SaveChanges();
            return model.Bcid;
        }
        #endregion

        #region 更新行卡信息
        /// <summary>
        /// 更新行卡信息
        /// </summary>
        /// <param name="CardMerchant">修改对象</param>
        /// <returns></returns>
        public bool Update(BankCard model, FlashPayContext flashPayContext = null)
        {
            _context.Entry<BankCard>(model);
            _context.SaveChanges();
            return true;
        }
        #endregion

        #region 银行额外限制
        /// <summary>
        /// 根据银行卡信息
        /// </summary>
        public BankCardExtraLimit GetByCardNumber(string cardNumber, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);
            return _flashPayContext.BankCardExtraLimit.Where(x => x.CardNumber == cardNumber).FirstOrDefault();
        }

        /// <summary>
        /// 银行额外限制【新增行卡信息】
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public string BankCardExtraLimitAdd(BankCardExtraLimit model, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);

            _flashPayContext.BankCardExtraLimit.Add(model);
            _flashPayContext.SaveChanges();
            return model.CardNumber;
        }
        /// <summary>
        /// 银行额外限制【更新行卡信息】
        /// </summary>
        /// <param name="CardMerchant">修改对象</param>
        /// <returns></returns>
        public bool BankCardExtraLimitUpdate(BankCardExtraLimit model, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);

            _flashPayContext.Entry<BankCardExtraLimit>(model);
            _flashPayContext.SaveChanges();
            return true;
        }
        #endregion

        #region 更改银行卡启用状态
        /// <summary>
        /// 更改银行卡启用状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateEnableStatus(int bcId,sbyte enableStatus)
        {
            var model = _context.BankCard.Where(p => p.Bcid.Equals(bcId)).FirstOrDefault();
            if (model != null)
            {
                model.EnableStatus = enableStatus;
                _context.SaveChanges();
                return true;
            }
            else
            {
                throw new Exception("当前记录不存在！");
            }
        }
        #endregion

        #region 刪除銀行卡
        /// <summary>
        /// 刪除銀行卡
        /// </summary>
        /// <param name="bcid">系统编号</param>
        /// <returns></returns>
        public bool DeleteByBcId(int bcId)
        {
            var model = _context.BankCard.Find(bcId);
            if (model != null)
            {
                model.CardNumber = $"{model.CardNumber}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
                model.EnableStatus = (sbyte)EnableStatus.删除.GetHashCode();
                model.CardName = $"{model.CardName}(删除)";
                _context.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 作废
        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="bcId"></param>
        /// <returns></returns>
        public bool Obsolete(int bcId)
        {
            var model = _context.BankCard.Where(p => p.Bcid.Equals(bcId)).FirstOrDefault();
            if (model != null)
            {
                model.CardType = (sbyte)CardType.作废卡.GetHashCode();
                model.EnableStatus = (sbyte)EnableStatus.禁用.GetHashCode();
                model.UpdateDate = DateTime.Now;
                _context.SaveChanges();
                return true;
            }
            else
            {
                throw new Exception("当前记录不存在！");
            }
        }
        #endregion

        #region 获取所有銀行卡记录
        /// <summary>
        /// 获取所有銀行卡记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public List<BankCard> GetByCardNumber(BankQuery query)
        {
            //多条件查询
            var where = PredicateBuilder.True<BankCard>();
            //不等于自己
            if (query.NoEqualBcId.HasValue)
            {
                where = where.And(c => c.Bcid != query.NoEqualBcId.Value);
            }

            //卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                where = where.And(c => c.CardNumber == query.CardNumber);
            }

            var list = _context.BankCard.Where(where.Compile()).ToList();

            return list;
        }

        /// <summary>
        /// 获取所有銀行卡记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public List<BankCard> GetList(BankQuery query)
        {
            //多条件查询
            var where = PredicateBuilder.True<BankCard>();

            //不等于自己
            if (query.NoEqualBcId.HasValue)
            {
                where = where.And(c => c.Bcid != query.NoEqualBcId.Value);
            }

            //订单号
            if (query.OrderNo.HasValue)
            {
                where = where.And(c => c.OrderNo == query.OrderNo);
            }

            //订单号
            if (query.CompanyId.HasValue)
            {
                where = where.And(c => c.CompanyId == query.CompanyId);
            }

            //卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                where = where.And(c => c.CardNumber.Contains(query.CardNumber));
            }

            //卡号
            if (!string.IsNullOrEmpty(query.CardName))
            {
                where = where.And(c => c.CardName.Contains(query.CardName));
            }

            //卡类型
            if (query.CardType.HasValue)
            {
                where = where.And(c => c.CardType == query.CardType);
            }

            //卡类型
            if (query.CardTypes != null && query.CardTypes.Any())
            {
                where = where.And(c => query.CardTypes.Contains(c.CardType));
            }

            //银行卡使用状态
            if (query.UsingStatus.HasValue)
            {
                where = where.And(c => c.UsingStatus == query.UsingStatus.Value);
            }

            //银行卡启用状态
            if (query.EnableStatusArray != null && query.EnableStatusArray.Any())
            {
                where = where.And(c => query.EnableStatusArray.Contains(c.EnableStatus));
            }

            //网类型
            if (query.UsbType.HasValue)
            {
                where = where.And(c => c.UsbType == query.UsbType.Value);
            }

            var list = _context.BankCard.Where(where.Compile()).ToList();

            return list;
        }

    /// <summary>
    /// 获取所有銀行卡记录
    /// </summary>
    /// <param name="query">查询条件</param>
    /// <returns>List<CardMerchant></returns>
    public List<BankPagerResponse> GetList()
    {
        var q = from bc in _context.BankCard
                join ui in _context.UserInfo on bc.CreateUid equals ui.UId
                select new BankPagerResponse
                {
                    BcId = bc.Bcid,
                    OrderNo = bc.OrderNo,
                    DisplayOrderNo = bc.OrderNo.ToString(),
                    CompanyId = ui.UCompanyId,
                    BankCardCompanyId = bc.CompanyId,
                    //CompanyName,
                    //CompanyNameEN,
                    BankName = bc.BankName,
                    CardName = bc.CardName,
                    CardNumber = bc.CardNumber,
                    SecCardNumber = bc.SecCardNumber,
                    CardType = bc.CardType,
                    UsingStatus = bc.UsingStatus,
                    EnableStatus = bc.EnableStatus,
                    PaymentInterval = bc.PaymentStart.ToString("#0.00") + "-" + bc.PaymentEnd.ToString("#0.00"),
                    PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                    DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                    CrossBankPay = bc.CrossBankPay,
                    DepositType = bc.DepositType,
                    CreateName = ui.ULoginName,
                    CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
                };
        return q.ToList();
    }
    #endregion

        #region 获取公司层级
        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public List<CompanyResponse> GetCompany(int companyId,int level = 2)
        {
            var companyRequest = new Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<Company>>();

            _companyDao.Get(companyList, companyRequest, level);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                    });
                }
            }
            return companyResponse;
        }

        //获取CompanyID集合
        public List<int> GetCompanyIDList(int companyId,int level=2)
        {
            var companyIds = new List<int>();
            var companys = this.GetCompany(companyId, level);

            foreach (var item in companys)
            {
                companyIds.Add(item.CompanyID);
            }
            return companyIds;
        }

        #endregion

        #region 银行卡分页
        /// <summary>
        /// 银行卡分页
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns></returns>
        public DataGrid<BankPagerResponse> GetPager(BankQuery query)
        {
            #region 搜索公司列表
            var where = PredicateBuilder.True<Company>();
            //卡号
            if (!string.IsNullOrEmpty(query.CompanyName))
            {
                where = where.And(c => c.CompanyName.Contains(query.CompanyName));
            }
            var searchCompanyList = _context.Company.Where(where.Compile()).ToList();
            #endregion

            var q = from bc in _context.BankCard
                    join ui in _context.UserInfo on bc.CreateUid equals ui.UId

                    join or in _context.OrderRecord on bc.OrderNo equals or.OrderNo
                    join cm in _context.CardMerchant on or.Cmid equals cm.Cmid

                    where bc.CardType != (sbyte)CardType.作废卡.GetHashCode()
                    select new BankPagerResponse
                    {
                        BcId = bc.Bcid,
                        OrderNo = bc.OrderNo,
                        DisplayOrderNo = bc.OrderNo.ToString(),
                        CompanyId = ui.UCompanyId,
                        BankCardCompanyId = bc.CompanyId,
                        //CompanyName,
                        //CompanyNameEN,
                        BankName = bc.BankName,
                        CardName = bc.CardName,
                        CardNumber = bc.CardNumber,
                        CardNumberText = Util.WebUtil.SetCardNumber(bc.CardNumber),
                        SecCardNumber = Util.WebUtil.SetCardNumber(bc.SecCardNumber),
                        CardType = bc.CardType,
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        PaymentInterval = bc.PaymentStart.ToString("#0.00")+" - "+bc.PaymentEnd.ToString("#0.00"),
                        PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                        DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                        CrossBankPay = bc.CrossBankPay,
                        PaymentType = bc.PaymentType,
                        DepositType = bc.DepositType,
                        CreateName = ui.ULoginName,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        CMCode = cm.Cmcode,//卡商代号
                        AliPayCardName = bc.AliPayCardName,
                        Remark = bc.Remark
                    };

            //订单号
            if (query.OrderNo.HasValue)
            {
                q = q.Where(c => c.OrderNo == query.OrderNo);
            }

            //银行名称
            if (!string.IsNullOrEmpty(query.BankName))
            {
                q = q.Where(c => c.BankName.Contains(query.BankName));
            }

            //卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
            }

            //卡号
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.CardName.Contains(query.CardName));
            }

            //卡类型
            if (query.CardType.HasValue)
            {
                q = q.Where(c => c.CardType == query.CardType);
            }

            //卡类型
            if (query.CardTypes != null && query.CardTypes.Any())
            {
                q = q.Where(c => query.CardTypes.Contains(c.CardType));
            }

            //银行卡使用状态
            if (query.UsingStatus.HasValue)
            {
                q = q.Where(c => c.UsingStatus == query.UsingStatus.Value);
            }

            //银行卡启用状态
            if (query.EnableStatusArray != null && query.EnableStatusArray.Any())
            {
                q = q.Where(c => query.EnableStatusArray.Contains(c.EnableStatus));
            }

            //网类型
            if (query.UsbType.HasValue)
            {
                q = q.Where(c => c.UsbType == query.UsbType.Value);
            }

            //公司层级
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }

            //搜索公司名称
            if (!string.IsNullOrEmpty(query.CompanyName))
            {
                var searchCompanyIds = searchCompanyList.Select(p => p.CompanyId).ToList();
                q = q.Where(c => searchCompanyIds.Contains(c.BankCardCompanyId));
            }
            //状态
            if (query.AuthStatus.HasValue)
            {
                if (query.AuthStatus.Value == AuthStatus.未分配公司.GetHashCode())
                    q = q.Where(c => c.BankCardCompanyId == 0);
                else
                    q = q.Where(c => c.BankCardCompanyId > 0);
            }
            //支付宝姓名
            if (!string.IsNullOrEmpty(query.AliPayCardName))
            {
                q = q.Where(c => c.AliPayCardName.Contains(query.AliPayCardName));
            }
            return new DataGrid<BankPagerResponse>
            {
                Total = q.Count(),
                Rows = q.OrderByDescending(r => r.CreateDate).Skip((query.Page.Value - 1) * query.Rows.Value).Take(query.Rows.Value).ToList(),
                Success = true
            };
        }
        #endregion

        #region 库存卡分页
        /// <summary>
        /// 库存卡分页
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<SpareBankCardResponse> GetSparePager(StockQuery query)
        {
            var editAuth = "";

            if (query.UserPermission.Contains("BankCardSpare0003")) {
                editAuth = "BankCardSpare0003";
            }
            var q = from bc in _context.BankCard
                    join ui in _context.UserInfo on bc.CreateUid equals ui.UId
                    join or in _context.OrderRecord on bc.OrderNo equals or.OrderNo
                    join cm in _context.CardMerchant on or.Cmid equals cm.Cmid
                    
                    select new SpareBankCardResponse
                    {
                        CompanyId = ui.UCompanyId,
                        ReceiptUID = or.ReceiptUid,
                        PayUID = or.PayUid,
                        Bcid = bc.Bcid,
                        OrderNo = bc.OrderNo.ToString(),
                        BankName = bc.BankName,
                        CardNumber = bc.CardNumber,
                        CardNumberText = Util.WebUtil.SetCardNumber(bc.CardNumber),
                        SecCardNumber = Util.WebUtil.SetCardNumber(bc.SecCardNumber),
                        CardName = bc.CardName,
                        CardType = bc.CardType,
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        LoginName = bc.LoginName,
                        PasswordLogin = bc.PasswordLogin,
                        PasswordQuery = bc.PasswordQuery,
                        PasswordPay = bc.PasswordPay,
                        PasswordShield = bc.PasswordShield,
                        UsbType = bc.UsbType,
                        OriginalPassword = bc.OriginalPassword,
                        AccountBank = bc.AccountBank,
                        DocumentNumber = bc.DocumentNumber,
                        PhoneNumber = bc.PhoneNumber,
                        PaymentStart = bc.PaymentStart,
                        PaymentEnd = bc.PaymentEnd,
                        PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                        DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                        CrossBankPay = bc.CrossBankPay,
                        DepositType = bc.DepositType,
                        AliPayCardName = bc.AliPayCardName,
                        Remark = bc.Remark,
                        CreateUid = bc.CreateUid,
                        CreateName = ui.ULoginName,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        CMCode= cm.Cmcode,
                        EditAuth = editAuth
                    };
            //订单号
            if (query.OrderNo != null && query.OrderNo > 0)
            {
                q = q.Where(c => c.OrderNo.Contains(query.OrderNo.ToString()));
            }
            //银行名称
            if (!string.IsNullOrEmpty(query.BankName))
            {
                q = q.Where(c => c.BankName.Contains(query.BankName));
            }
            //银行卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
            }
            //银行卡用户名
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.CardName.Contains(query.CardName));
            }
            //银行卡类型
            if (query.CardType.HasValue)
            {
                q = q.Where(c => c.CardType == query.CardType);
            }
            //银行卡启用状态
            if (query.EnableStatus.HasValue)
            {
                q = q.Where(c => c.EnableStatus == query.EnableStatus.Value);
            }
            //银行卡启用状态
            if (query.EnableStatusList != null && query.EnableStatusList.Any())
            {
                q = q.Where(c => query.EnableStatusList.Contains(c.EnableStatus));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }
            //支付宝姓名
            if (!string.IsNullOrEmpty(query.AliPayCardName))
            {
                q = q.Where(c => c.AliPayCardName.Contains(query.AliPayCardName));
            }
            if (query.UserPermission != null)
            {
                if (query.UserPermission.Contains("BankCardSpare0007") && query.UserPermission.Contains("BankCardSpare0006"))
                {
                    //全部未完成订单卡、全部已完成订单卡
                    var orderIds = _context.OrderRecord.Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
                else if (query.UserPermission.Contains("BankCardSpare0007"))
                {
                    //全部未完成订单卡（√）
                    var orderIds = _context.OrderRecord.Where(p => p.DepositUid == 0 || p.ReceiptUid == 0 || p.PayUid == 0).Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
                else if (query.UserPermission.Contains("BankCardSpare0006"))
                {
                    //全部已完成订单卡（√）
                    var orderIds = _context.OrderRecord.Where(p => p.DepositUid > 0 && p.ReceiptUid > 0 && p.PayUid > 0).Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
                else
                {
                    //默认
                    var orderIds = _context.OrderRecord.Where(p => p.DepositUid > 0 && p.PayUid == 0 && p.CreateUid == query.CreateUid).Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
            }

            return new DataGrid<SpareBankCardResponse>
            {
                Total = q.Count(),
                Rows = q.OrderByDescending(r => r.CreateDate).Skip((query.Page.Value - 1) * query.Rows.Value).Take(query.Rows.Value).ToList(),
                Success = true
            };
        }
        #endregion

        #region B2B库存卡分页
        /// <summary>
        /// 库存卡分页
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<B2BSpareBankCardResponse> GetB2BSparePager(B2BSpareBankCardQuery query)
        {
            var q = from bc in _context.BankCard
                    join ui in _context.UserInfo on bc.CreateUid equals ui.UId

                    //join or in _context.OrderRecord on bc.OrderNo equals or.OrderNo
                    //join cm in _context.CardMerchant on or.Cmid equals cm.Cmid

                    select new B2BSpareBankCardResponse
                    {
                        CompanyId = ui.UCompanyId,
                        //ReceiptUID = or.ReceiptUid,
                        //PayUID = or.PayUid,
                        Bcid = bc.Bcid,
                        //OrderNo = bc.OrderNo.ToString(),
                        BankName = bc.BankName,
                        CardNumber = bc.CardNumber,
                        CardNumberText = Util.WebUtil.SetCardNumber(bc.CardNumber),
                        SecCardNumber = Util.WebUtil.SetCardNumber(bc.SecCardNumber),
                        CardName = bc.CardName,
                        CardType = bc.CardType,
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        LoginName = bc.LoginName,
                        PasswordLogin = bc.PasswordLogin,
                        PasswordQuery = bc.PasswordQuery,
                        PasswordPay = bc.PasswordPay,
                        PasswordShield = bc.PasswordShield,
                        UsbType = bc.UsbType,
                        OriginalPassword = bc.OriginalPassword,
                        AccountBank = bc.AccountBank,
                        DocumentNumber = bc.DocumentNumber,
                        PhoneNumber = bc.PhoneNumber,
                        PaymentStart = bc.PaymentStart,
                        PaymentEnd = bc.PaymentEnd,
                        PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                        DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                        CrossBankPay = bc.CrossBankPay,
                        DepositType = bc.DepositType,
                        Remark = bc.Remark,
                        CreateUid = bc.CreateUid,
                        CreateName = ui.ULoginName,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        UpdateDate=bc.UpdateDate,
                        AliPayCardName = bc.AliPayCardName
                        //CMCode = cm.Cmcode==null?"": cm.Cmcode//卡商代号
                    };
            //银行名称
            if (!string.IsNullOrEmpty(query.BankName))
            {
                q = q.Where(c => c.BankName.Contains(query.BankName));
            }
            //银行卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
            }
            //银行卡用户名
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.CardName.Contains(query.CardName));
            }
            //银行卡类型
            if (query.CardType.HasValue)
            {
                q = q.Where(c => c.CardType == query.CardType);
            }
            //银行卡启用状态
            if (query.EnableStatus.HasValue)
            {
                q = q.Where(c => c.EnableStatus == query.EnableStatus.Value);
            }
            //银行卡启用状态
            if (query.EnableStatusList != null && query.EnableStatusList.Any())
            {
                q = q.Where(c => query.EnableStatusList.Contains(c.EnableStatus));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }
            //作废时间
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                q = q.Where(c => c.UpdateDate >= Convert.ToDateTime(query.StartTime) && c.UpdateDate <= Convert.ToDateTime(query.EndTime));
            }
            if (query.EnableStatus.HasValue)
            {
                q = q.Where(c => c.EnableStatus == query.EnableStatus.Value);
            }
            //支付宝姓名
            if (!string.IsNullOrEmpty(query.AliPayCardName))
            {
                q = q.Where(c => c.AliPayCardName.Contains(query.AliPayCardName));
            }
            //return new PagedList<SpareBankCardResponse>
            //{
            //    TData = q.OrderByDescending(r => r.CreateDate).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList(),
            //    CurrentPageIndex = query.CurrentPageIndex.Value,
            //    TotalCount = q.Count(),
            //    Success = true
            //};

            return new DataGrid<B2BSpareBankCardResponse>()
            {
                Total = q.Count(),
                Rows = q.OrderByDescending(r => r.CreateDate).Skip((query.Page.Value - 1) * query.Rows.Value).Take(query.Rows.Value).ToList(),
                Success = true
            };
        }
        #endregion

        #region B2B银行卡分页
        /// <summary>
        /// 银行卡分页
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns></returns>
        public DataGrid<B2BBankCardResponse> GetB2BPager(B2BBankCardQuery query)
        {
            #region 搜索公司列表
            var where = PredicateBuilder.True<Company>();
            //卡号
            if (!string.IsNullOrEmpty(query.CompanyName))
            {
                where = where.And(c => c.CompanyName.Contains(query.CompanyName));
            }
            var searchCompanyList = _context.Company.Where(where.Compile()).ToList();
            #endregion

            var q = from bc in _context.BankCard
                    join ui in _context.UserInfo on bc.CreateUid equals ui.UId 
                    where new List<int>() { (sbyte)CardType.收款卡, (sbyte)CardType.中转卡, (sbyte)CardType.付款卡, (sbyte)CardType.备用卡 }.Contains(bc.CardType)
                    select new B2BBankCardResponse
                    {
                        BcId = bc.Bcid,
                        OrderNo = bc.OrderNo,
                        DisplayOrderNo = bc.OrderNo.ToString(),
                        CompanyId = ui.UCompanyId,
                        BankCardCompanyId = bc.CompanyId,
                        //CompanyName,
                        //CompanyNameEN,
                        BankName = bc.BankName,
                        CardName = bc.CardName,
                        CardNumber = bc.CardNumber,
                        CardNumberText = Util.WebUtil.SetCardNumber(bc.CardNumber),
                        SecCardNumber = bc.SecCardNumber,
                        CardType = bc.CardType,
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        PaymentInterval = bc.PaymentStart.ToString("#0.00") + " - " + bc.PaymentEnd.ToString("#0.00"),
                        PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                        DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                        CrossBankPay = bc.CrossBankPay,
                        DepositType = bc.DepositType,
                        CreateName = ui.ULoginName,
                        AliPayCardName = bc.AliPayCardName,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
                    };

            //订单号
            if (query.OrderNo.HasValue)
            {
                q = q.Where(c => c.OrderNo == query.OrderNo);
            }

            //银行名称
            if (!string.IsNullOrEmpty(query.BankName))
            {
                q = q.Where(c => c.BankName.Contains(query.BankName));
            }

            //卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
            }

            //卡号
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.CardName.Contains(query.CardName));
            }

            //卡类型
            if (query.CardType.HasValue)
            {
                q = q.Where(c => c.CardType == query.CardType);
            }

            //卡类型
            if (query.CardTypes != null && query.CardTypes.Any())
            {
                q = q.Where(c => query.CardTypes.Contains(c.CardType));
            }

            //银行卡使用状态
            if (query.UsingStatus.HasValue)
            {
                q = q.Where(c => c.UsingStatus == query.UsingStatus.Value);
            }

            //银行卡启用状态
            if (query.EnableStatusArray != null && query.EnableStatusArray.Any())
            {
                q = q.Where(c => query.EnableStatusArray.Contains(c.EnableStatus));
            }

            //网类型
            if (query.UsbType.HasValue)
            {
                q = q.Where(c => c.UsbType == query.UsbType.Value);
            }

            //公司层级
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }

            //搜索公司名称
            if (!string.IsNullOrEmpty(query.CompanyName))
            {
                var searchCompanyIds = searchCompanyList.Select(p => p.CompanyId).ToList();
                q = q.Where(c => searchCompanyIds.Contains(c.BankCardCompanyId));
            }
            //状态
            if (query.AuthStatus.HasValue)
            {
                if (query.AuthStatus.Value == AuthStatus.未分配公司.GetHashCode())
                    q = q.Where(c => c.BankCardCompanyId == 0);
                else
                    q = q.Where(c => c.BankCardCompanyId > 0);
            }
            //支付宝姓名
            if (!string.IsNullOrEmpty(query.AliPayCardName))
            {
                q = q.Where(c => c.AliPayCardName.Contains(query.AliPayCardName));
            }
            return new DataGrid<B2BBankCardResponse>()
            {
                Total = q.Count(),
                Rows = q.OrderByDescending(r => r.CreateDate).Skip((query.Page.Value - 1) * query.Rows.Value).Take(query.Rows.Value).ToList(),
                Success = true
            };
        }

        /// <summary>
        /// 获取有效银行卡
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns></returns>
        public PagedList<ValidCardResponse> GetValidCard(ValidCardQuery query)
        {
            var q = from bc in _context.BankCard
                    join ui in _context.UserInfo on bc.CreateUid equals ui.UId
                    where bc.BankCode != "MFB" && bc.UsingStatus == (sbyte)UsingStatus.有效 && bc.EnableStatus == (sbyte)EnableStatus.有效 && bc.CompanyId>0 && new List<int>() { (sbyte)CardType.收款卡, (sbyte)CardType.中转卡, (sbyte)CardType.付款卡, (sbyte)CardType.安全卡 }.Contains(bc.CardType)
                    select new ValidCardResponse
                    {
                        BcId = bc.Bcid,
                        OrderNo = bc.OrderNo,
                        DisplayOrderNo = bc.OrderNo.ToString(),
                        CompanyId = ui.UCompanyId,
                        BankCardCompanyId = bc.CompanyId,
                        //CompanyName,
                        //CompanyNameEN,
                        BankName = bc.BankName,
                        BankCode = bc.BankCode,
                        CardName = bc.CardName,
                        CardNumber = bc.CardNumber,
                        CardNumberText = Util.WebUtil.SetCardNumber(bc.CardNumber),
                        SecCardNumber = bc.SecCardNumber,
                        CardType = bc.CardType,
                        CardTypeText = WebUtil.CardType(bc.CardType),
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        PaymentInterval = bc.PaymentStart.ToString("#0.00") + " - " + bc.PaymentEnd.ToString("#0.00"),
                        PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                        DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                        CrossBankPay = bc.CrossBankPay,
                        DepositType = bc.DepositType,
                        CreateName = ui.ULoginName,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")
                    };

            //银行名称
            if (!string.IsNullOrEmpty(query.BankName))
            {
                q = q.Where(c => c.BankName.Contains(query.BankName));
            }
            //卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
            }
            //卡类型
            if (query.CardTypes != null && query.CardTypes.Any())
            {
                q = q.Where(c => query.CardTypes.Contains(c.CardType));
            }
            //卡号
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.CardName.Contains(query.CardName));
            }
            return new PagedList<ValidCardResponse>()
            {
                TData = q.OrderByDescending(r => r.CreateDate).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList(),
                CurrentPageIndex = query.CurrentPageIndex.Value,
                TotalCount = q.Count()
            };
        }
        #endregion

        #region 中转卡
        /// <summary>
        /// 获取中转卡
        /// </summary>
        /// <param name="bcId"></param>
        public TransportCard GetTransportCard(int bcId, FlashPayContext flashPayContext = null)
        {
            return _context.TransportCard.FirstOrDefault(p => p.Bcid == bcId);
        }

        /// <summary>
        /// 新增中转卡
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public int TransportCardAdd(TransportCard model, FlashPayContext flashPayContext = null)
        {
            _context.TransportCard.Add(model);
            _context.SaveChanges();
            return model.Bcid;
        }

        /// <summary>
        /// 更新中转卡
        /// </summary>
        /// <param name="CardMerchant">修改对象</param>
        /// <returns></returns>
        public bool TransportCardUpdate(TransportCard model, FlashPayContext flashPayContext = null)
        {
            _context.Entry<TransportCard>(model);
            _context.SaveChanges();
            return true;
        }
        #endregion

        #region 银行卡类型记录
        /// <summary>
        /// 新增银行卡类型记录
        /// </summary>
        /// <param name="userInfo">银行卡类型记录对象</param>
        /// <returns></returns>
        public int BankCardTypeRecordAdd(BankCardTypeRecord model, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);
            _flashPayContext.BankCardTypeRecord.Add(model);
            _flashPayContext.SaveChanges();
            return model.Id;
        }
        #endregion

        #region 获取公司的所有付款卡
        /// <summary>
        /// 获取公司的所有付款卡
        /// </summary>
        /// <param name="request"></param>
        public void GetCompanyPaymentCard(CompanyPaymentCardQuery request)
        {
        }
        #endregion

        #region 更新AdjustBalanceRID为Null
        /// <summary>
        /// 更新AdjustBalanceRID
        /// </summary>
        /// <returns></returns>
        public JResult UpdateAdjustBalanceRID(int bcId)
        {
            var result = new JResult() {
                Success = false
            };

            try
            {
                var bankCard = this.GetById(bcId); ;
                if (bankCard == null) {
                    throw new Exception("银行卡记录不存在！");
                }

                //if (bankCard.EnableStatus != BankCardEnableStatus.禁用.GetHashCode())
                //{
                //    throw new Exception("银行卡记录必须为禁用状态！");
                //}

                if (!bankCard.AdjustBalanceRid.HasValue) {
                    throw new Exception("该银行卡记录已处理！");
                }

                var sql = $"update BankCard set AdjustBalanceRID=null where  bcid={bankCard.Bcid}";

                var updateStatusPaymentRecord = _context.Database.ExecuteSqlCommand(sql);
                if (updateStatusPaymentRecord <= 0)
                {
                    throw new Exception("数据库操作失败！");
                }

                result.Success = true;
                result.SuccessMessage = "操作成功！";
            }
            catch (Exception ex) {
                result.ErrorMessage = ex.Message;
            }
            return result;
        }
        #endregion

        #region 银行卡还原
        /// <summary>
        /// 银行卡还原
        /// </summary>
        /// <param name="bcId">系统编号</param>
        /// <returns></returns>
        public JResult Restitute(int bcId) {

            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var bankCard = this.GetById(bcId); ;
                if (bankCard == null)
                {
                    throw new Exception("银行卡记录不存在！");
                }

                if (bankCard.CardType != (sbyte)CardType.作废卡)
                {
                    throw new Exception("银行卡记录类型已发生改变！");
                }

                var sql = $"update BankCard set CardType={(sbyte)CardType.备用卡},EnableStatus={(sbyte)EnableStatus.未授权},UsingStatus={(sbyte)UsingStatus.冻结.GetHashCode()} where  bcid={bankCard.Bcid}";

                var updateStatusPaymentRecord = _context.Database.ExecuteSqlCommand(sql);
                if (updateStatusPaymentRecord <= 0)
                {
                    throw new Exception("数据库操作失败！");
                }

                //日志
                _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = $"银行卡还原成功,编号:{bcId}";
                _logDao.Insert(_logRecord);

                result.Success = true;
                result.SuccessMessage = "操作成功！";
            }
            catch (Exception ex)
            {
                //日志
                _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = $"银行卡还原失败,编号:{bcId}";
                _logDao.Insert(_logRecord);

                result.ErrorMessage = ex.Message;
            }
            return result;
        }
        #endregion

        #region 作废卡
        /// <summary>
        /// 作废卡
        /// </summary>
        /// <param name="request"></param>
        public PagedList<ObsoleteBankCardResponse> GetObsoleteBankCard(ObsoleteBankCardQuery query)
        {
            var q = from bc in _context.BankCard
                    join ui in _context.UserInfo on bc.CreateUid equals ui.UId

                    //join or in _context.OrderRecord on bc.OrderNo equals or.OrderNo
                    //join cm in _context.CardMerchant on or.Cmid equals cm.Cmid

                    select new ObsoleteBankCardResponse
                    {
                        CompanyId = ui.UCompanyId,
                        //ReceiptUID = or.ReceiptUid,
                        //PayUID = or.PayUid,
                        Bcid = bc.Bcid,
                        //OrderNo = bc.OrderNo.ToString(),
                        BankName = bc.BankName,
                        CardNumber = Util.WebUtil.SetCardNumber(bc.CardNumber),
                        SecCardNumber = Util.WebUtil.SetCardNumber(bc.SecCardNumber),
                        CardName = bc.CardName,
                        CardType = bc.CardType,
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        LoginName = bc.LoginName,
                        PasswordLogin = bc.PasswordLogin,
                        PasswordQuery = bc.PasswordQuery,
                        PasswordPay = bc.PasswordPay,
                        PasswordShield = bc.PasswordShield,
                        UsbType = bc.UsbType,
                        OriginalPassword = bc.OriginalPassword,
                        AccountBank = bc.AccountBank,
                        DocumentNumber = bc.DocumentNumber,
                        PhoneNumber = bc.PhoneNumber,
                        PaymentStart = bc.PaymentStart,
                        PaymentEnd = bc.PaymentEnd,
                        PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                        DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                        CrossBankPay = bc.CrossBankPay,
                        DepositType = bc.DepositType,
                        Remark = bc.Remark,
                        CreateUid = bc.CreateUid,
                        CreateName = ui.ULoginName,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        UpdateDate = bc.UpdateDate,
                        //CMCode = cm.Cmcode==null?"": cm.Cmcode//卡商代号
                    };
            //银行名称
            if (!string.IsNullOrEmpty(query.BankName))
            {
                q = q.Where(c => c.BankName.Contains(query.BankName));
            }
            //银行卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
            }
            //银行卡用户名
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.CardName.Contains(query.CardName));
            }
            //银行卡类型
            if (query.CardType.HasValue)
            {
                q = q.Where(c => c.CardType == query.CardType);
            }
            //银行卡启用状态
            if (query.EnableStatus.HasValue)
            {
                q = q.Where(c => c.EnableStatus == query.EnableStatus.Value);
            }
            //银行卡启用状态
            if (query.EnableStatusList != null && query.EnableStatusList.Any())
            {
                q = q.Where(c => query.EnableStatusList.Contains(c.EnableStatus));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }
            //作废时间
            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                q = q.Where(c => c.UpdateDate >= Convert.ToDateTime(query.StartTime) && c.UpdateDate <= Convert.ToDateTime(query.EndTime));
            }
            if (query.EnableStatus.HasValue)
            {
                q = q.Where(c => c.EnableStatus == query.EnableStatus.Value);
            }

            return new PagedList<ObsoleteBankCardResponse>
            {
                TData = q.OrderByDescending(r => r.CreateDate).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList(),
                CurrentPageIndex = query.CurrentPageIndex.Value,
                TotalCount = q.Count(),
                Success = true
            };
        }
        #endregion

        #region 安全卡
        /// <summary>
        /// 安全卡
        /// </summary>
        /// <param name="query"></param>
        public void SafetyCard(SafetyCardQuery query)
        {

        }
        #endregion

        #region 根据公司数组获取银行卡
        /// <summary>
        /// 根据公司数组获取银行卡
        /// </summary>
        /// <param name="companyIds"></param>
        /// <returns></returns>
        public List<CompanyBankCardResponse> GetCompanyBankCard(List<int> companyIds)
        {
            var q = from bc in _context.BankCard.Where(c => companyIds.Contains(c.CompanyId))
                       select new CompanyBankCardResponse
                       {
                           BcId = bc.Bcid,
                           CardName = bc.CardName,
                           CardType = bc.CardType,
                           BankCode = bc.BankCode,
                           CardNumber = bc.CardNumber,
                       };

            return q.ToList();
        }
        #endregion

        //根据订单号获取卡商代号
        public string GetCMCodeByOrderNo(long orderNo) {

            using (var _contexts = new FlashPayContext())
            {
                string str = string.Empty;
                if (orderNo==0) return str;
                var orderItem = _contexts.OrderRecord.Find(orderNo);
                if (orderItem == null) return str;
                var cardMerchant = _contexts.CardMerchant.Find(orderItem.Cmid);
                if (cardMerchant == null) return str;
                str = cardMerchant.Cmcode;
                return str;
            }
        }

    }
}
